package com.yunxi.service.dubboService.impl.market;

import com.aliyun.openservices.shade.org.apache.commons.lang3.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.yunxi.core.util.BeanTools;
import com.yunxi.core.util.StringUtil;
import com.yunxi.market.pojo.*;
import com.yunxi.market.service.MarketActivityDubboService;
import com.yunxi.model.market.MarketActivity;
import com.yunxi.model.market.MarketActivityDispatch;
import com.yunxi.model.market.MarketActivityFeedback;
import com.yunxi.model.market.MarketActivityItem;
import com.yunxi.service.dubboService.impl.OrderOemManagerDubboServiceImpl;
import com.yunxi.service.localService.CodeCreateService;
import com.yunxi.service.localService.impl.CodeCreateServiceImpl;
import com.yunxi.service.localService.market.MarketActivityDispatchService;
import com.yunxi.service.localService.market.MarketActivityFeedbackService;
import com.yunxi.service.localService.market.MarketActivityItemService;
import com.yunxi.service.localService.market.MarketActivityService;
import java.math.BigDecimal;
import org.apache.xmlbeans.impl.store.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 市场活动主表 服务实现类
 * </p>
 *
 * @author 
 * @since 2019-08-17
 */
public class MarketActivityDubboServiceImpl implements MarketActivityDubboService {

    private final Logger logger = LoggerFactory.getLogger(MarketActivityDubboServiceImpl.class);

    @Autowired
    @Qualifier(value = "marketActivityServiceImpl")
    MarketActivityService marketActivityService;

    @Autowired
    @Qualifier(value = "marketActivityItemServiceImpl")
    MarketActivityItemService marketActivityItemService;

    @Autowired
    @Qualifier(value = "marketActivityFeedbackServiceImpl")
    MarketActivityFeedbackService marketActivityFeedbackService;

    @Autowired
    @Qualifier(value = "marketActivityDispatchServiceImpl")
    MarketActivityDispatchService marketActivityDispatchService;

    @Autowired
    @Qualifier(value = "codeCreateServiceImpl")
    CodeCreateService codeCreateServiceImpl;

    @Override
    public MarketActivityVO getById(String id) throws InvocationTargetException, IllegalAccessException {
        MarketActivity marketActivity = marketActivityService.getById(id);
        MarketActivityVO marketActivityVO = new MarketActivityVO();
        BeanUtils.copyProperties(marketActivity,marketActivityVO);
        return marketActivityVO;
    }

    @Override
    public void saveOrUpdate(MarketActivityVO marketActivityVO) throws InvocationTargetException, IllegalAccessException {
        MarketActivity marketActivity = new MarketActivity();
        BeanUtils.copyProperties(marketActivityVO,marketActivity);
        marketActivityService.saveOrUpdate(marketActivity);
    }

    @Override
    public void removeById(String id) {
    marketActivityService.removeById(id);
    }

    @Override
    public PageInfo<MarketActivityVO> findPageByVO(MarketActivityVO marketActivityVO, Integer pageNum, Integer pageSize) throws InvocationTargetException, IllegalAccessException {
      PageInfo<MarketActivityVO> pageInfo = marketActivityService.pageByVo(marketActivityVO,pageNum,pageSize);
      return pageInfo;
    }

    @Override
    public void removeByListVo(List<MarketActivityVO> marketActivityVOList) throws IllegalAccessException, InvocationTargetException, InstantiationException {
        marketActivityService.removeByListVo(marketActivityVOList);
    }

    @Override
    public List listByVo(MarketActivityVO marketActivityVO) {
      return marketActivityService.listByVo(marketActivityVO);
    }

    /**
     * 主机厂市场活动主数据查询
     * @param vo
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    @Transactional
    public PageInfo<MarketActivityQueryRespVO> queryMarketActivityForApprovePage(MarketActivityQueryReqVO vo, int pageNum, int pageSize) {
        return marketActivityService.queryMarketActivityForApprovePage(vo,pageNum,pageSize);
    }

    /**
     * 渠道商市场活动主数据查询
     * @param vo
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    @Transactional
    public PageInfo<MarketActivityQueryRespVO> queryMarketActivityForPage(MarketActivityQueryReqVO vo, int pageNum, int pageSize) {
        return marketActivityService.queryMarketActivityForPage(vo,pageNum,pageSize);
    }


    /**
     * 点击"查看"市场活动明细查询
     * @param vo
     * @return
     */
    @Override
    @Transactional
    public MarketActivityDetailsQueryRespVO queryMarketActivityDetails(MarketActivityDetailsQueryReqVO vo){

        if(vo == null || vo.getActivityId() == null){
            logger.info("VO对象为Null，请核实！");
            throw new RuntimeException("VO对象为Null，请核实！");
        }

        QueryWrapper qwMarketActivity = new QueryWrapper();
        qwMarketActivity.eq("ACTIVITY_ID",vo.getActivityId());
        MarketActivity marketActivity =  marketActivityService.getOne(qwMarketActivity);

        if(marketActivity == null){
            logger.info("市场活动，主表数据为空！");
            return null;
        }

        QueryWrapper qwMarketActivityItem = new QueryWrapper();
        qwMarketActivityItem.eq("ACTIVITY_CODE",marketActivity.getActivityCode());
        List<MarketActivityItem> marketActivityItems = marketActivityItemService.list(qwMarketActivityItem);

        MarketActivityQueryRespVO  marketActivityEntity = new MarketActivityQueryRespVO();
        BeanUtils.copyProperties(marketActivity,marketActivityEntity);

        List<MarketActivityItemQueryRespVO> marketActivityItemEntities = new ArrayList<MarketActivityItemQueryRespVO>();

        for(MarketActivityItem item : marketActivityItems){
            MarketActivityItemQueryRespVO entity = new MarketActivityItemQueryRespVO();
            BeanUtils.copyProperties(item,entity);
            marketActivityItemEntities.add(entity);
        }

        MarketActivityDetailsQueryRespVO result = new MarketActivityDetailsQueryRespVO();

        result.setMarketActivity(marketActivityEntity);
        result.setMarketActivityItems(marketActivityItemEntities);
        return result;
    }

    /**
     * 点击"提报"查看详情
     * @return
     */
    @Override
    @Transactional
    public MarketActivityDetailsQueryRespVO queryMarketActivityDetailsByToPut(MarketActivityDetailsQueryReqVO vo){

        if(vo == null || vo.getActivityId() == null){
            logger.info("VO对象为Null，请核实！");
            throw new RuntimeException("VO对象为Null，请核实！");
        }

        //
        //主档数据查询
        QueryWrapper qwMarketActivity = new QueryWrapper();
        qwMarketActivity.eq("ACTIVITY_ID",vo.getActivityId());
        MarketActivity marketActivity =  marketActivityService.getOne(qwMarketActivity);

        if(marketActivity == null){
            logger.info("市场活动，主表数据为空！");
            return null;
        }

        //
        //明细数据查询
        MarketActivityItemQueryReqVO marketActivityItemQueryReqVO = new MarketActivityItemQueryReqVO();
        marketActivityItemQueryReqVO.setPartnerCode(vo.getPartnerCode());
        marketActivityItemQueryReqVO.setActivityCode(marketActivity.getActivityCode());
        List<MarketActivityItemQueryRespVO> marketActivityItemEntities = marketActivityItemService.queryMarketActivityItemByList(marketActivityItemQueryReqVO);

        MarketActivityQueryRespVO  marketActivityEntity = new MarketActivityQueryRespVO();
        BeanUtils.copyProperties(marketActivity,marketActivityEntity);

        MarketActivityDetailsQueryRespVO result = new MarketActivityDetailsQueryRespVO();

        result.setMarketActivity(marketActivityEntity);
        result.setMarketActivityItems(marketActivityItemEntities);
        return result;
    }


    /**
     * 保存市场活动
     * @param vo
     * @return
     */
    @Override
    @Transactional
    public boolean saveMarketActivity(MarketActivitySaveReqVO vo) {

        if(vo == null || vo.getMarketActivity() == null || vo.getMarketActivityItems() == null){
            logger.info("VO对象为Null，请核实！");
            throw new RuntimeException("VO对象为Null，请核实！");
        }

        MarketActivityQueryRespVO marketActivityEntity =  vo.getMarketActivity();
        List<MarketActivityItemQueryRespVO> marketActivityItemEntities = vo.getMarketActivityItems();

        MarketActivity marketActivity = new MarketActivity();
        marketActivity.setAuditStatus(2);
        BeanUtils.copyProperties(marketActivityEntity,marketActivity);

        String marketActivityCode = codeCreateServiceImpl.createCode("MA",CodeCreateServiceImpl.DATE_FORMAT_FOUR,3);
        marketActivity.setActivityCode(marketActivityCode);

        // 查询渠道商名称（名称1，名称2，名称3）
        String partnerName= marketActivityService.queryPartnerNameByCodes(marketActivity.getPartnerCode());
        marketActivity.setPartnerName(partnerName);

        List<MarketActivityItem> marketActivityItems = new ArrayList<MarketActivityItem>();


        for (MarketActivityItemQueryRespVO item : marketActivityItemEntities) {
            MarketActivityItem entity = new MarketActivityItem();
            BeanUtils.copyProperties(item, entity);
            entity.setActivityCode(marketActivityCode);
            entity.setPartnerCode(vo.getMarketActivity().getPartnerCode());
            marketActivityItems.add(entity);
        }

        marketActivityService.save(marketActivity);
        marketActivityItemService.saveBatch(marketActivityItems);

        return true;
    }

    /**
     * 修改并保存市场活动
     * @param vo
     * @return
     */
    @Override
    @Transactional
    public boolean updateMarketActivity(MarketActivityModifyReqVO vo){

        if(vo == null || vo.getMarketActivity() == null || vo.getMarketActivityItems() == null){
            logger.info("VO对象为Null，请核实！");
            throw new RuntimeException("VO对象为Null，请核实！");
        }

        MarketActivityQueryRespVO marketActivityEntity =  vo.getMarketActivity();
        List<MarketActivityItemQueryRespVO> marketActivityItemEntities = vo.getMarketActivityItems();

        MarketActivity marketActivity = new MarketActivity();
        BeanUtils.copyProperties(marketActivityEntity,marketActivity);

        // 查询渠道商名称（名称1，名称2，名称3）
        String partnerName= marketActivityService.queryPartnerNameByCodes(marketActivity.getPartnerCode());
        marketActivity.setPartnerName(partnerName);

        marketActivityService.updateById(marketActivity);


        for(MarketActivityItemQueryRespVO item : marketActivityItemEntities){
            if(item.getDataType() == 3){ //表示修改
                MarketActivityItem marketActivityItem = new MarketActivityItem();
                BeanUtils.copyProperties(item,marketActivityItem);
                marketActivityItem.setPartnerCode(marketActivityEntity.getPartnerCode());
                QueryWrapper qw = new QueryWrapper();
                qw.eq("ITEM_ID",item.getItemId());

                marketActivityItemService.update(marketActivityItem,qw);
            }else if(item.getDataType() == 1){ //表示新增
                MarketActivityItem marketActivityItem = new MarketActivityItem();
                BeanUtils.copyProperties(item, marketActivityItem);
                marketActivityItem.setActivityCode(marketActivity.getActivityCode());
                marketActivityItem.setPartnerCode(marketActivityEntity.getPartnerCode());
                marketActivityItemService.save(marketActivityItem);
            }else if(item.getDataType() == 2){ //表示删除
                marketActivityItemService.removeById(item.getItemId());
            }
        }
        return true;
    }

    /**
     * 提报
     * @param vo
     * @return
     */
    @Override
    @Transactional
    public boolean toPut(MarketActivityToPutReqVO vo){

        List<MarketActivityDispatchToPutReqVO> voEntities = vo.getDispatchList();

        BigDecimal realTotalCost = BigDecimal.ZERO;
        for(MarketActivityDispatchToPutReqVO entity : voEntities){
            QueryWrapper qw = new QueryWrapper();
            qw.eq("DETAILS_ID",entity.getDetailsId());
            MarketActivityDispatch dispatch = new MarketActivityDispatch();
            dispatch.setRealItemCost(entity.getRealItemCost()+"");
            marketActivityDispatchService.update(dispatch,qw);

            QueryWrapper itemQw = new QueryWrapper();
            itemQw.eq("ITEM_ID",entity.getDetailsId());
            MarketActivityItem item = new MarketActivityItem();
            item.setRealItemCost(entity.getRealItemCost());
            marketActivityItemService.update(item, itemQw);

            realTotalCost = realTotalCost.add(entity.getRealItemCost());
        }

        MarketActivityFeedback marketActivityFeedback = new MarketActivityFeedback();
        marketActivityFeedback.setFeedbackInfo(vo.getFeedbackInfo());
        marketActivityFeedback.setFeedbackBy(vo.getUserCode());
        marketActivityFeedback.setActivityCode(vo.getActivityCode());
        marketActivityFeedback.setPartnerCode(vo.getPartnerCode());
        marketActivityFeedbackService.save(marketActivityFeedback);

        QueryWrapper qw = new QueryWrapper();
        qw.eq("ACTIVITY_CODE",vo.getActivityCode());

        MarketActivity marketActivity = new MarketActivity();
        marketActivity.setAuditStatus(4);
        marketActivity.setResultContent(vo.getFeedbackInfo());
        marketActivity.setRealTotalCost(realTotalCost);
        marketActivityService.update(marketActivity,qw);

        return true;
    }

    @Override
    public boolean delMarketActivityItem(MarketActivityItemDelReqVO vo) {
        //
        //删除市场活动项
        marketActivityItemService.removeById(vo.getMarketActivityItemId());
        //
        //更新
        return true;
    }

    /**
     * 审核
     * @param vo
     * @return
     */
    @Override
    @Transactional
    public boolean audit(MarketActivityAuditReqVO vo){

        if(vo == null || vo.getActivityCode() == null){
            logger.info("VO对象为Null，请核实！");
            throw new RuntimeException("VO对象为Null，请核实！");
        }

         QueryWrapper qw = new QueryWrapper();
         qw.eq("ACTIVITY_CODE",vo.getActivityCode());

         MarketActivity marketActivity = new MarketActivity();
         marketActivity.setRejectInfo(vo.getRejectInfo());
         marketActivity.setAuditDate(new Date());
         marketActivity.setAuditStatus(vo.getAuditStatus());
         marketActivity.setAuditBy(vo.getAuditBy());

         marketActivityService.update(marketActivity,qw);

         if(vo.getAuditStatus() != 1){
             return true;
         }
         List<MarketActivityItem> marketActivityItemEntities = marketActivityItemService.list(qw);

         String[] partnerCodes = marketActivityItemEntities.get(0).getPartnerCode().split(",");
         //
         //分发
         for(String partnerCode : partnerCodes){
            for(MarketActivityItem item : marketActivityItemEntities){
                MarketActivityDispatch marketActivityDispatch = new MarketActivityDispatch();
                marketActivityDispatch.setActivityCode(vo.getActivityCode());
                marketActivityDispatch.setPartnerCode(partnerCode);
                marketActivityDispatch.setItemId(item.getItemId());
                marketActivityDispatchService.save(marketActivityDispatch);
            }
         }
        return true;
    }
}
